﻿using AutoMapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Implement;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.Rolees;
using MediatR;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.Rolees
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        IBaseRepository<Role> Role;
        IMapper mapper;
        DatabaseContext db;
        public UpdateRoleCommandHandler(IBaseRepository<Role> Role, IMapper mapper, DatabaseContext db)
        {
            this.Role = Role;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> apiResult = new ApiResult<int>();
            try
            {
                var Chename = db.SqlSugar.Queryable<Role>().Where(c => c.Role_Name == request.Role_Name
&& !c.IsDel&& c.Role_Id!= request.Role_Id).Count();
                if (Chename > 0)
                {
                    apiResult.Code = ApiEnum.error;
                    apiResult.Message = "该角色已存在";
                    apiResult.Data = 0;
                    return apiResult;
                }
                var slist = Role.GetQuery().Where(x => x.Role_Id == request.Role_Id).First();
                var list = mapper.Map(request, slist);
                var cout = Role.UpdateAsync(list).Result;
                if (cout > 0)
                {
                    apiResult.Code = ApiEnum.success;
                    apiResult.Message = "更新成功";
                    apiResult.Data = 1;
                }
                else
                {
                    apiResult.Code = ApiEnum.error;
                    apiResult.Message = "更新失败";
                    apiResult.Data = 0;
                }
            }

            catch (Exception ex)
            {
                apiResult.Code = ApiEnum.error;
                apiResult.Message = ex.Message;

            }

            return apiResult;
        }
    }
}
